package com.training.service;

import com.training.entity.Chapter; // Import Chapter entity
import com.training.entity.Course; // Import Course entity
import com.training.mapper.ChapterMapper; // Import ChapterMapper interface
import com.training.mapper.CourseMapper; // Import CourseMapper interface
import org.springframework.beans.factory.annotation.Autowired; // Import Autowired annotation
import org.springframework.stereotype.Service; // Import Service annotation
import org.springframework.transaction.annotation.Transactional; // Import Transactional annotation

import java.util.List; // Import List collection

@Service // Mark this as a Service class
public class ChapterService {

    @Autowired // Auto-inject ChapterMapper instance
    private ChapterMapper chapterMapper;

    @Autowired // Auto-inject CourseMapper instance (NEW: needed to update course chapter count)
    private CourseMapper courseMapper;

    /**
     * Get all non-logically deleted chapters for a given course ID, ordered by chapter_order.
     * @param couId Course ID
     * @return List of Chapter objects
     */
    public List<Chapter> getChaptersByCourseId(Long couId) {
        return chapterMapper.findChaptersByCourseId(couId);
    }

    /**
     * Get a non-logically deleted chapter by its ID.
     * @param id Chapter ID
     * @return Chapter object, null if not found or logically deleted
     */
    public Chapter getChapterById(Long id) {
        return chapterMapper.findChapterById(id);
    }

    /**
     * Save chapter information (new or update).
     * Handles setting default values and automatically generating chapter order for new chapters.
     * Also updates the course's chapter count (couCataNum).
     * @param chapter Chapter object to save
     * @return Number of affected rows
     */
    @Transactional // Add transaction management
    public int saveChapter(Chapter chapter) {
        // Set default values for NOT NULL fields that have them (if they are currently null)
        if (chapter.getChapterDuration() == null) {
            chapter.setChapterDuration(0);
        }
        if (chapter.getDeleted() == null) {
            chapter.setDeleted(0);
        }

        int affectedRows;
        // For new chapters (id is null), automatically generate chapter order
        if (chapter.getId() == null) {
            Integer maxOrder = chapterMapper.findMaxChapterOrderByCourseId(chapter.getCouId());
            // If no chapters exist for this course, start from 1, otherwise maxOrder + 1
            chapter.setChapterOrder((maxOrder == null ? 0 : maxOrder) + 1);
            affectedRows = chapterMapper.insertChapter(chapter);

            // NEW: If a new chapter is inserted, increment the course's chapter count
            if (affectedRows > 0) {
                Course course = courseMapper.findCourseById(chapter.getCouId());
                if (course != null) {
                    course.setCouCataNum(course.getCouCataNum() + 1);
                    courseMapper.updateCourse(course); // Update the course in the database
                }
            }
        } else {
            // For existing chapters (update operation), simply update
            affectedRows = chapterMapper.updateChapter(chapter);
        }
        return affectedRows;
    }

    /**
     * Logically delete a chapter record.
     * After deletion, re-sequence the chapter orders for subsequent chapters in the same course.
     * Also updates the course's chapter count (couCataNum).
     * @param id Chapter ID to delete
     * @return true if deleted successfully, false otherwise
     */
    @Transactional // Add transaction management
    public boolean deleteChapter(Long id) {
        Chapter chapterToDelete = chapterMapper.findChapterById(id);
        if (chapterToDelete == null) {
            return false; // Chapter not found or already deleted
        }

        int affectedRows = chapterMapper.deleteChapter(id);
        if (affectedRows > 0) {
            // After deleting, decrement the order of subsequent chapters in the same course
            chapterMapper.decrementChapterOrders(chapterToDelete.getCouId(), chapterToDelete.getChapterOrder());

            // NEW: Decrement the course's chapter count
            Course course = courseMapper.findCourseById(chapterToDelete.getCouId());
            if (course != null && course.getCouCataNum() > 0) {
                course.setCouCataNum(course.getCouCataNum() - 1);
                courseMapper.updateCourse(course); // Update the course in the database
            }
            return true;
        }
        return false;
    }

    /**
     * Get the next available chapter order for a given course.
     * @param couId Course ID
     * @return The next chapter order (e.g., if max is 5, returns 6)
     */
    public Integer getNextChapterOrder(Long couId) {
        Integer maxOrder = chapterMapper.findMaxChapterOrderByCourseId(couId);
        return (maxOrder == null ? 0 : maxOrder) + 1;
    }
}
